package com.inetAddress;

import org.junit.Test;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddressExample {
    /**
     * 创建一个InetAddress对象
     * @throws UnknownHostException
     */
    @Test
    public void test1() throws UnknownHostException {
        // 使用主机名创建InetAddress对象
        InetAddress googleAddress = InetAddress.getByName("www.google.com");
        // IP地址
        System.out.println("Google IP: "+googleAddress.getHostAddress());
        // 主机名
        System.out.println("Google Hostname: " + googleAddress.getHostName());

        //  使用IP地址创建InetAddress对象
        InetAddress localByIpString = InetAddress.getByName("127.0.0.1");
        // IP地址
        System.out.println("Local by IP String: " + localByIpString.getHostAddress());
    }

    @Test
    public void test2() throws UnknownHostException {
        //一个域名可能对应多个IP地址
        InetAddress[] allByName = InetAddress.getAllByName("www.google.com");
        System.out.println("Google的所有IP地址:");
        for (InetAddress inetAddress : allByName) {
            System.out.println(inetAddress.getHostAddress());
        }
    }

    @Test
    public void test3() throws UnknownHostException {
        //getLocalHost()方法返回本地主机的InetAddress对象
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println("本地主机的IP地址: " + localHost.getHostAddress());
        System.out.println("本地主机的主机名: " + localHost.getHostName());
    }



}
